package lion.dev.image.format;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import lion.dev.image.FileFormatWriter;

public class FileFormatClass extends FileFormatWriter {

	private String name;

	public FileFormatClass() {
		super("Java Source", "text/plain", ".java");
	}

	@Override
	public boolean canRead(String extension) {

		return false;
	}

	@Override
	public void writeImage(OutputStream out, BufferedImage image) throws IOException {

		int width = image.getWidth();
		int height = image.getHeight();
		PrintStream ps = new PrintStream(out);
		ps.println("import java.awt.*;");
		ps.println("import java.awt.image.*;");
		ps.println();
		ps.println("public class " + name + " {");
		ps.println("\tprivate static Image image;");
		ps.println("\tprivate static int width = " + width + ";");
		ps.println("\tprivate static int height = " + height + ";");
		ps.println("\tprivate static int[] pixels = {");
		int i = 0;
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (i == 0) {
					ps.print("\t\t");
				} else if (i++ % 10 == 0) {
					ps.println();
					ps.print("\t\t");
				}
				i++;
				ps.print(image.getRGB(x, y));
				ps.print(",");
			}
		}
		ps.println();
		ps.println("\t};");
		ps.println();
		ps.println("\tpublic static Image getImage() {");
		ps.println("\t\tif (image != null)");
		ps.println("\t\t\treturn image;");
		ps.println(
				"\t\treturn image = Toolkit.getDefaultToolkit.createImage(new MemoryImageSource(width, height, ColorModel.getRGBdefault(), pixels, 0, width));");
		ps.println("\t}");
		ps.println("}");
		ps.close();
	}
}
